﻿// 项目：	Guan.CMS.Web - Guan.CMS
// 文件名：	ToProductCategoryTree.cs
//
// 修改时间：2013-03-10 18:09
// 修改人：	Cooclsee

using System.Collections.Generic;
using System.Linq;
using Guan.CMS.Model.Entities;
using Guan.CMS.Web.ViewModels.ProductCategory;

namespace Guan.CMS.Web.Helpers
{
    public static class ToProductCategoryTreeHelper
    {
        public static IEnumerable<ProductCategoryTree> ToProductCategoryTree(this IEnumerable<ProductCategory> list, bool isExpanded = false)
        {
            if (list != null && (list = list.ToList()).Any())
            {
                var level1List = list.Where(c => c.ParentId == null || c.ParentId == 0).ToList();
                if (level1List.Any())
                {
                    foreach (var item in level1List)
                    {
                        //父级
                        var itemToAdd = new ProductCategoryTree { Id = item.Id, Name = item.Name };
                        //子级
                        var children = list.Where(c => c.ParentId == item.Id).ToList();

                        if (isExpanded) //平铺/展开方式
                        {
                            yield return itemToAdd;
                            foreach (var sub in children)
                            {
                                var child = new ProductCategoryTree
                                {
                                    Id = sub.Id,
                                    Name = item.Name + " > " + sub.Name,
                                    ParentId = item.Id
                                };
                                yield return child;
                            }
                        }
                        else//树形式
                        {
                            if (itemToAdd.Children == null)
                            {
                                itemToAdd.Children = new List<ProductCategoryTree>();
                            }
                            foreach (var sub in children)
                            {
                                var child = new ProductCategoryTree
                                {
                                    Id = sub.Id,
                                    Name = sub.Name,
                                    ParentId = item.Id
                                };
                                itemToAdd.Children.Add(child);
                            }
                            yield return itemToAdd;
                        }
                    }
                }
            }
        }
    }
}